//
//  SearchVC.m
//  ProjectsOne
//
//  Created by iOS开发 on 2018/7/11.
//  Copyright © 2018年 iOS开发. All rights reserved.
//

#import "SearchVC.h"
#import "SearchView.h"
#import "SearchHeadCell.h"
#import "SearchCell.h"
#import "SearchModel.h"
#import "LeftFlowLayout.h"
#import "SearchResultVC.h"
#import "NSString+Custom.h"

@interface SearchVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate>

@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) SearchView *searchView;

@property (nonatomic, strong) NSMutableArray *styleArr;

@end

@implementation SearchVC

- (void)dealloc{
    NSLog(@"%@释放",NSStringFromClass([self class]));
}

- (SearchView *)searchView {
    if (!_searchView) {
        _searchView = [[SearchView alloc] initWithFrame:CGRectMake(10, 100, WIDTH, 44)];
        _searchView.searchFiled.delegate = self;
    }
    return _searchView;
}

- (UICollectionView *)collection {
    if (!_collection) {
        LeftFlowLayout *flowLayout = [[LeftFlowLayout alloc] initWthType:AlignWithLeft];
        flowLayout.minimumInteritemSpacing = 15;
        flowLayout.minimumLineSpacing = 15;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 15, 10, 15);
        
        _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
        _collection.delegate = self;
        _collection.dataSource = self;
        _collection.backgroundColor = [UIColor whiteColor];
        _collection.showsVerticalScrollIndicator = NO;
        _collection.showsHorizontalScrollIndicator = NO;
        _collection.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        [_collection registerClass:[SearchCell class] forCellWithReuseIdentifier:@"keywordCell"];
        [_collection registerClass:[SearchHeadCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"styleCell"];
    }
    return _collection;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addSwipe];
    [self setNav];
    [self request];
}

- (void)setNav {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = self.searchView;
    [self.view addSubview:self.collection];
    
    // 取消
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor colorWithHexString:@"ffa631"] forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelButton addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    cancelButton.frame = CGRectMake(0, 0, 40, 40);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
}

#pragma mark - data
- (void)request {
    // 热门搜索 申请数据
    self.styleArr = [NSMutableArray array];
    SearchModel *model = [[SearchModel alloc] init];
    [model setValue:@"热门搜索" forKey:@"style"];
    [self.styleArr addObject:model];
    
    // 判断本地是否有历史搜索 插入数组第一位
    [self judgeHistoryData];
}

// 判断本地是否有历史搜索 插入数组第一位
- (void)judgeHistoryData {
    // 判断原来是否有历史搜索 有则移除 重新赋值
    SearchModel *firstModel = self.styleArr.firstObject;
    if ([firstModel.style isEqualToString:@"历史搜索"]) {
        [self.styleArr removeObjectAtIndex:0];
    }
    
    // 本地获取历史搜索
    NSArray *fmdbArr = [[FMDBManager shareManage] getAllData];
    if (fmdbArr.count) {
        NSMutableArray <KeywordModel *>*keywordArr = [NSMutableArray array];
        for (NSString *keyword in fmdbArr) {
            KeywordModel *model = [[KeywordModel alloc] init];
            [model setValue:keyword forKey:@"keyword"];
            [keywordArr addObject:model];
        }
        SearchModel *historyModel = [[SearchModel alloc] init];
        [historyModel setValue:@"历史搜索" forKey:@"style"];
        [historyModel setValue:keywordArr forKey:@"searchArr"];
        [self.styleArr insertObject:historyModel atIndex:0];
    }
    [self.collection reloadData];
}

// 更新本地数据
- (void)updateHistoryData:(SearchResultVC *)vc text:(NSString *)text {
    @weakify(self);
    vc.block = ^{
        @strongify(self);
        [self judgeHistoryData];
    };
    // 保存本地
    if ([[FMDBManager shareManage] checkKeywordFromDB:text]) {
        // 如果本地有数据 删除此条数据重新添加
        [[FMDBManager shareManage] deleteDataWithKeyword:text];
    }
    [[FMDBManager shareManage] insertionDataWithKeyword:text];
}



#pragma mark - collectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.styleArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SearchModel *model = self.styleArr[section];
    return model.searchArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"keywordCell" forIndexPath:indexPath];
    
    SearchModel *model = self.styleArr[indexPath.section];
    cell.keywordLabel.text = [model.searchArr[indexPath.row] keyword];
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchModel *model = self.styleArr[indexPath.section];
    return CGSizeMake([model.searchArr[indexPath.row] keywordWidth], 30);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    SearchHeadCell *cell = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"styleCell" forIndexPath:indexPath];
    
    SearchModel *model = self.styleArr[indexPath.section];
    [cell setStyle:model.style];
    
    [self deleteDB:cell];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    SearchModel *model = self.styleArr[section];
    return model.searchArr.count == 0 ? CGSizeZero:CGSizeMake(WIDTH, 52.5f);
}

#pragma mark - select
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchCell *cell = (SearchCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    _searchView.searchFiled.text = cell.keywordLabel.text;
    [self textFieldShouldReturn:_searchView.searchFiled];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    SearchResultVC *vc = [[SearchResultVC alloc] initWithSearchText:textField.text];
    [self.navigationController pushViewController:vc animated:YES];
    // 更新本地数据
    [self updateHistoryData:vc text:textField.text];
    return YES;
}



#pragma mark - action
// 删表
- (void)deleteDB:(SearchHeadCell *)cell {
    @weakify(self);
    cell.dbBlock = ^{
        @strongify(self);
        [[FMDBManager shareManage] deleteData];
        [self judgeHistoryData];
    };
}

// 添加右滑返回
- (void)addSwipe {
    self.view.backgroundColor = [UIColor whiteColor];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(popVC:)];
    swipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipe];
}

// 返回
- (void)popVC:(UISwipeGestureRecognizer *)swipe {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 取消
- (void)cancel:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - override
// 输入限制
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    // 不让输入表情
    if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage] || [NSString stringContainsEmoji:string]) {
        return NO;
    }
    
    // 限制10长度
    if (range.length == 1 && string.length == 0) {
        return YES;
    }
    else if (self.searchView.searchFiled.text.length >= 10) {
        self.searchView.searchFiled.text = [textField.text substringToIndex:10];
        return NO;
    }
    return YES;
}

// 状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setShadowImage:nil];
    // 状态栏颜色
    [self preferredStatusBarStyle];
    [self setStatusBarBackgroundColor:[UIColor colorWithHexString:@"1a1a1a"]];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.navigationController.isBeingDismissed) {
        [self setStatusBarBackgroundColor:[UIColor clearColor]];        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
